// $Id: CountInputStream.java 11 2008-11-28 18:10:07Z moyekj@yahoo.com $

package com.hme.tivo.videostream;

import java.io.InputStream;
import java.io.IOException;

// Extend InputStream to keep track of # bytes read
public class CountInputStream extends InputStream {
    private transient boolean alreadycounting;
    private long count = 0;
    protected volatile InputStream in;

    public CountInputStream(InputStream in) {
        this.in = in;
    }

    public int read(byte[] b) throws IOException {
        boolean wascounting = alreadycounting;
        alreadycounting = true;
        int found = super.read(b);
        alreadycounting = wascounting;
        if (!alreadycounting && found > 0)
           this.count += found;
        return found;
    }

    public int read(byte[] b, int off, int len) throws IOException {
        boolean wascounting = alreadycounting;
        alreadycounting = true;
        int found = super.read(b, off, len);
        alreadycounting = wascounting;
        if (!alreadycounting && found > 0)
           this.count += found;
        return found;
    }

    public int read() throws IOException {
       boolean wascounting = alreadycounting;
       alreadycounting = true;
       int found = in.read();
       alreadycounting = wascounting;
       if (!alreadycounting && found > 0)
          this.count++;
       return found;
    }
    
   public long skip(long bytes) {
      boolean wascounting = alreadycounting;
      alreadycounting = true;
      long skipped = 0;
      try {
         skipped = super.skip(bytes);
      } catch (IOException e) {
         e.printStackTrace();
      }
      alreadycounting = wascounting;
      if (!alreadycounting)
         this.count += skipped;
      return skipped;
   }

    public long getCount() {
        return this.count;
    }
    
    public void close() throws IOException {
       super.close();
    }
}